package com.wzz.download.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.StringTokenizer;

import android.util.Log;


public class HttpUtils {
  private static final String TAG = "TestDown";
  private HttpURLConnection httpConnection;
  /**下载文件总大小*/
  private long fileSizeDown ;
  /**下载文件名称*/
  private String fileNameDown;



  /**
   * 连接http服务器
   * @param destUrl 下载路径
   * @param bytes 从哪个字节处开始下载
   * @return 返回服务器输入流
   * @throws IOException
   */
  public InputStream connectHttp(String destUrl,long bytes) throws IOException{
    URL url = new URL(destUrl);
    httpConnection = (HttpURLConnection)url.openConnection(); 
    httpConnection.setRequestProperty("User-Agent","NetFox"); 
    //    httpUrlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
    /**设置从那个字节处开始下*/ 
    //内网不认识头报416
    //    httpConnection.setRequestProperty("RANGE","bytes="+bytes+"");
    httpConnection.connect(); 
    int code = httpConnection.getResponseCode() ;
    Log.d(TAG,"code:"+code+"");
    if(code == 200){
      setHttpConnection(httpConnection);
      fileSizeDown = httpConnection.getContentLength();
      fileNameDown = extractFileNameFromURL(url);
      return httpConnection.getInputStream();
    }
    return null;

  }
  /**
   * 获取文件名
   * @param url 获取文件名的URL
   * @return 文件名称
   */
  private static final String extractFileNameFromURL(URL url){
    StringTokenizer st = new StringTokenizer(url.getFile(), "/");
    String fileName = null;
    while (st.hasMoreTokens()){
      fileName = st.nextToken();
    }
    return fileName;
  }



  public long getFileSizeDown() {
    return this.fileSizeDown;
  }

  public void setFileSizeDown(long fileSizeDown) {
    this.fileSizeDown = fileSizeDown;}


  public String getFileNameDown() {
    return this.fileNameDown;
  }

  public void setFileNameDown(String fileNameDown) {
    this.fileNameDown = fileNameDown;}

  public HttpURLConnection getHttpConnection() {
    return this.httpConnection;
  }
  public void setHttpConnection(HttpURLConnection httpConnection) {
    this.httpConnection = httpConnection;}
}
